<?php
namespace app\admin\controller;

//use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Lang;
use app\common\WeiXin;
use think\Db;
use think\Log;

/**
 * ============================================================================
 * 佳皿一站式,酒水服务类综合平台
 * ============================================================================
 * 版权所有 2019-2028 成都佳皿商贸有限公司，并保留所有权利。
 * 网站地址: http://www.91buys.com
 * ============================================================================
 * 控制器
 */
class Livegoods extends AdminControl {

    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/'.config('default_lang').'/livegoods.lang.php');
    }
    
    function index()
    {
        /**
         * 显示直播位管理界面
         */
        //查询商品状态
        $goodsIds = db('live_goods')->where('status','neq',2)->column('goodsId');
        if($goodsIds){
            $url = 'https://api.weixin.qq.com/wxa/business/getgoodswarehouse?access_token='.(new WeiXin())->getAccessToken();
            $returnData = $this->http_post($url,json_encode(['goods_ids'=>$goodsIds]));
            $returnData = json_decode($returnData,true);
            if(isset($returnData['errcode']) && $returnData['errcode'] == 0){
                foreach ($returnData['goods'] as $goods){
                    db('live_goods')->where('goodsId',$goods['goods_id'])->setField('status',$goods['audit_status']);
                }
            }
        }
        $condition = array();
        $search_name = trim(input('get.search_name'));
        if ($search_name != '') {
            $condition['name'] = $search_name;
        }
        $ap_list= model('livegoods')->getAppadvpositionList($condition,'10');
        $this->assign('ap_list',$ap_list);
        $this->assign('showpage', model('livegoods')->page_info->render());
        
        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        
        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /**
     *
     * 新增直播位
     */
    public function ap_add() {
        if (!request()->isPost()) {
            $ap['ap_isuse']=1;
            $this->assign('ap',$ap);
            return $this->fetch('ap_form');
        } else {
            $appadv_model = model('appadv');
            $insert_array['ap_name'] = trim(input('post.ap_name'));
            $insert_array['ap_intro'] = trim(input('post.ap_intro'));
            $insert_array['ap_isuse'] = intval(input('post.ap_isuse'));
            $insert_array['ap_width'] = intval(input('post.ap_width'));
            $insert_array['ap_height'] = intval(input('post.ap_height'));

            $adv_validate = validate('adv');
            if (!$adv_validate->scene('app_ap_add')->check($insert_array)) {
                $this->error($adv_validate->getError());
            }

            $result = $appadv_model->addAppadvposition($insert_array);

            if ($result) {
                $this->log(lang('ap_add_succ') . '[' . input('post.ap_name') . ']', null);
                dsLayerOpenSuccess(lang('ap_add_succ'),url('Appadv/index'));
            } else {
                $this->error(lang('ap_add_fail'));
            }
        }
    }

    /**
     *
     * 修改直播
     */
    public function adv_edit() {
        $adv_id = intval(input('param.adv_id'));
        $appadv_model = model('appadv');
        //获取指定直播
        $condition['adv_id'] = $adv_id;
        $adv = $appadv_model->getOneAppadv($condition);
        if (!request()->isPost()) {
            //获取直播列表
            $ap_list = $appadv_model->getAppadvpositionList();
            $this->assign('ap_list', $ap_list);
            $this->assign('adv', $adv);
            $this->assign('ref_url', get_referer());
            return $this->fetch('adv_form');
        } else {
            $param['adv_id'] = $adv_id;
            $param['ap_id'] = intval(input('post.ap_id'));
            $param['adv_title'] = trim(input('post.adv_name'));
            $param['adv_type'] = input('post.adv_type');
            $param['adv_typedate'] = input('post.adv_typedate');
            $param['adv_sort'] = input('post.adv_sort');
            $param['adv_enabled'] = input('post.adv_enabled');
            $param['adv_startdate'] = $this->getunixtime(trim(input('post.adv_startdate')));
            $param['adv_enddate'] = $this->getunixtime(trim(input('post.adv_enddate')));

            //上传至阿里云保存的路径
            $appAdvPath = config('oss_img_path.app_adv_path');
            switch ($param['ap_id']){
                case self::ADV_H5_PROMOTION_APID:
                    $appAdvPath = config('oss_img_path.app_promotion_path');
                    break;
                case self::ADV_H5_FLORAPID:
                    $appAdvPath = config('oss_img_path.app_floor_path');
                    break;
            }
            //上传文件保存路径
            $upload_file = BASE_UPLOAD_PATH . '/' . ATTACH_APPADV;
            if (!empty($_FILES['adv_code']['name'])) {
                $file = request()->file('adv_code');
                $info = $file->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT]);

                if ($info) {
                    //$insert_array['adv_code'] = $info->getFilename();
                    $insert_array['adv_code'] = config('ali_oss_upload').'_' .$_FILES['adv_code']['name'];
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
                $res = upload_img_to_oss($appAdvPath,'adv_code',$_FILES['adv_code']['name']);

                if($res['code'] != 10000)   $this->error($res['message']);
                //$info = $file->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($upload_file);
                $param['adv_code'] = $res['result'];  #阿里云上传还会拼接上前缀
            }

            $adv_validate = validate('adv');
            if (!$adv_validate->scene('app_adv_edit')->check($param)) {
                $this->error($adv_validate->getError());
            }

            $result = $appadv_model->editAppadv($param);

            if ($result>=0) {
                $this->log(lang('adv_change_succ') . '[' . input('post.ap_name') . ']', null);
                dsLayerOpenSuccess(lang('adv_change_succ'),input('post.ref_url'));
            } else {
                $this->error(lang('adv_change_fail'));
            }
        }
    }
    
    
    /**
     *
     * 直播管理
     */
    public function adv() {
        $appadv_model = model('appadv');
        $ap_id = intval(input('param.ap_id'));
        if (!request()->isPost()) {
            $condition = array();
            if ($ap_id) {
                $condition['ap_id'] = $ap_id;
            }
            $adv_info = $appadv_model->getAppadvList($condition, 20, '', '');
            $this->assign('adv_info', $adv_info);
            $ap_list = $appadv_model->getAppadvpositionList();
            $this->assign('ap_list', $ap_list);
            if ($ap_id) {
                $ap_condition=array();
                $ap_condition['ap_id']=$ap_id;
                $ap = $appadv_model->getOneAppadvposition($ap_condition); 
                $this->assign('ap_name', $ap['ap_name']);
            } else {
                $this->assign('ap_name', '');
            }

            $this->assign('show_page', $appadv_model->page_info->render());
            
            $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
            
            $this->setAdminCurItem('adv');
            return $this->fetch('adv_index');
        }
    }

    /**
     * 管理员添加直播
     */
    public function appadv_add() {
        $appadv_model = model('live');
        if (!request()->isPost()) {

            return $this->fetch('adv_form');
        } else {
            $insert_array = input('param.');
            if($insert_array['priceType'] == 2){
                if($insert_array['price'] < 0.01 || $insert_array['price2'] < 0.01 || $insert_array['price']>= $insert_array['price2']){
                    $this->error('价格错误');
                }
            }
            if($insert_array['priceType'] == 3){
                if($insert_array['price'] < 0.01 || $insert_array['price2'] < 0.01){
                    $this->error('价格错误');
                }
            }

            if (!empty($_FILES['coverImg']['name'])) {
                //上传文件保存路径
                $res = upload_img_to_oss(config('oss_img_path.app_live_path'),'coverImg',$_FILES['coverImg']['name']);
                $upload_file = BASE_UPLOAD_PATH . '/' . ATTACH_APPADV;
                $file = request()->file('coverImg');
                $info = $file->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($upload_file);
                $imgUrl = realpath($info->getPathname());
                $token  =  (new WeiXin)->getAccessToken();
                $URL ='https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$token.'&type=image';
                if(class_exists('\CURLFile')){  //7.0
                    $data = ['media' => new \CURLFile($imgUrl)];
                }else{  //5.6以及5.6以下
                    $data = array('media' => '@'.$imgUrl);
                }
                $result = $this->http_url($URL,$data);
                $data = @json_decode($result,true);
                if (isset($data['media_id'])) {
                    $insert_array['coverImgUrl'] = $data['media_id'];
                    if($res['code'] != 10000)
                        $param['coverImgUrl'] = $imgUrl;
                    else
                        $insert_array['coverImgUrl_1'] = $res['result'];  #阿里云上传还会拼接上前缀
                        @unlink($imgUrl);
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            }
            $adv_validate = validate('livegoods');
            if (!$adv_validate->scene('app_adv_add')->check($insert_array)) {
                $this->error($adv_validate->getError());
            }
            unset($insert_array['textfield']);
            Db::startTrans();
            try{
                //请求微信直播入口
                $token = (new WeiXin())->getAccessToken();
                $arr['goodsInfo'] = $insert_array;
//                $arr['goodsInfo']['url'] = 'pages/home/productdetails/productdetails?'.urlencode('goods_id='.$insert_array['goods_id']);
                $arr['goodsInfo']['url'] = 'pages/home/productdetails/productdetails?goods_id='.$insert_array['goods_id'];
                $url =  'https://api.weixin.qq.com/wxaapi/broadcast/goods/add?access_token='.$token;
                $returnData = $this->http_post($url,json_encode($arr));
                Log::write("$returnData","debug");
                $returnData = json_decode($returnData,true);
                if(isset($returnData['goodsId'])){
                    $insert_array['goodsId'] = $returnData['goodsId'];
                    $insert_array['auditId'] = $returnData['auditId'];
                    $insert_array['addTime'] = time();
                    $result = db('live_goods')->insertGetId($insert_array);
                    if($result){
                        Db::commit();
                        dsLayerOpenSuccess(lang('adv_add_succ'),url('livegoods/index'));
                    }
                }else{
                    Db::rollback();
                    $this->error($returnData['errmsg']);
                }
                Db::rollback();
                $this->error(lang('adv_add_fail'));
            } catch (\Exception $e) {
                // 回滚事务
                Log::write("{$e->getTraceAsString()}","debug");
                Db::rollback();
                $this->error(lang('adv_add_fail'));
            }

        }
    }

    /**直播专用
     * @param $url
     * @param null $data
     * @return mixed
     */
    private function http_post($url,$data = null){
        $headers = array("Content-type: application/json;charset='utf-8'","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    private function http_url($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     *
     * 修改直播位
     */
    public function ap_edit() {
        $ap_id = intval(input('param.ap_id'));

        $appadv_model = model('appadv');
        if (!request()->isPost()) {
            
            $condition['ap_id'] = $ap_id;
            $ap = $appadv_model->getOneAppadvposition($condition);
            $this->assign('ref_url', get_referer());
            $this->assign('ap', $ap);
            return $this->fetch('ap_form');
        } else {
            $param['ap_id'] = $ap_id;
            $param['ap_name'] = trim(input('post.ap_name'));
            $param['ap_intro'] = trim(input('post.ap_intro'));
            $param['ap_width'] = intval(trim(input('post.ap_width')));
            $param['ap_height'] = intval(trim(input('post.ap_height')));
            if (input('post.ap_isuse') != '') {
                $param['ap_isuse'] = intval(input('post.ap_isuse'));
            }
            $adv_validate = validate('adv');
            if (!$adv_validate->scene('app_ap_edit')->check($param)) {
                $this->error($adv_validate->getError());
            }

            $result = $appadv_model->editAppadvposition($param);

            if ($result>=0) {
                $this->log(lang('ap_change_succ') . '[' . input('post.ap_name') . ']', null);
                dsLayerOpenSuccess(lang('ap_change_succ'),input('post.ref_url'));
            } else {
                $this->error(lang('ap_change_fail'));
            }
        }
    }
    /**
     *
     * 获取UNIX时间戳
     */
    public function getunixtime($time) {
        $array = explode("-", $time);
        $unix_time = mktime(0, 0, 0, $array[1], $array[2], $array[0]);
        return $unix_time;
    }
    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => lang('ap_manage'),
                'url' => url('Livegoods/index')
            ),
        );
        $menu_array[] = array(
            'name' => 'adv_add',
            'text' => lang('adv_add'),
            'url' => "javascript:dsLayerOpen('".url('Livegoods/appadv_add', ['ap_id' => input('param.ap_id')])."','".lang('adv_add')."')"
        );
        return $menu_array;
    }

    /**
     * 删除商品
     */
    public function del(){
        $goodsId = input('param.goodsId');
        if(empty($goodsId))  ds_json_encode(10001, lang('请求参数错误'));
        $token = (new WeiXin())->getAccessToken();
        $url = 'https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token='.$token;
        $returnData = $this->http_post($url,json_encode(['goodsId'=>$goodsId]));
        $returnData = json_decode($returnData,true);
        if($returnData['errcode'] == 0){
            $res = db('live_goods')->where('goodsId',$goodsId)->delete();
            if($res)   ds_json_encode(10000, lang('ap_del_succ_1'));
        }
        ds_json_encode(10001, lang('ap_del_fail'));
    }

}
